<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { contextMenuProps, MouseMenuItem } from './menu';
import { getUid } from '@/utils/get';
import { Icon } from '@iconify/vue';

const props = defineProps<contextMenuProps>();
const uid = ref(`context-menu-${getUid()}`);
const menu = ref<HTMLElement | null>(null);

const hideAllContextMenu = () => {
  // TODO: hide all context menu
  const menuList = document.getElementsByClassName('context-menu');
  for (let i = 0; i < menuList.length; i++) {
    (menuList[i] as HTMLElement).style.display = 'none';
  }
};

const emitContextMenu = (event: Event) => {
  // TODO: emit context menu
  // hideAllContextMenu();
  // console.log(event);

  // return;

  const e = event || window.event;
  e.preventDefault();

  const target = e.target as HTMLElement;

  // 获取当前位置 和 到边界的距离
  // const { clientX, clientY } = e;
  const { left, top } = target.getBoundingClientRect();

  // TODO: show context menu
  if (!menu.value) return;
  menu.value.style.display = 'block';
  menu.value.style.opacity = '1';
  menu.value.style.left = `${left}px`;
  menu.value.style.top = `${top}px`;
};

const init = () => {
  menu.value = document.getElementById(uid.value);
  document.addEventListener('click', () => hideAllContextMenu());

  const dom = document.getElementById(props.domId);
  if (!dom) return;

  menu.value!.oncontextmenu = emitContextMenu;
};

const onClick = async (val: MouseMenuItem) => {
  new Promise(resolve => {
    resolve(val.click && val.click());
  }).then(() => {
    hideAllContextMenu();
  });
};

defineExpose({ emitContextMenu });

onMounted(() => init());
</script>
<template>
  <div
    :id="uid"
    class="context-menu opacity-0 absolute z-999 py-8px px-0 block w-120px border-solid border-1px border-gray-100 rounded-lg shadow-2xl"
  >
    <slot name="header"></slot>
    <ul class="list-none">
      <li
        class="text-size-14px py-1 px-4 w-full box-border hover:bg-blue-100"
        v-for="(item, index) in list"
        :key="index"
        @click="onClick(item)"
      >
        <Icon v-if="item.icon" :icon="item.icon" class="mr-1" />
        {{ item.label }}
      </li>
    </ul>
    <slot name="body"></slot>
    <slot name="footer"></slot>
  </div>
</template>
<style lang="scss" scoped>
.context-menu {
  display: none;
  background-color: var(--el-bg-color);
  transition: all 0.2s ease-in-out;
}
</style>
